package org.jeecg.modules.demo.allvipcard.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.allvipcard.entity.AllVipcard;
import org.jeecg.modules.demo.allvipcard.mapper.AllVipcardMapper;
import org.jeecg.modules.demo.allvipcard.service.IAllVipcardService;
import org.jeecg.modules.demo.basemembersharecoupon.entity.BaseMemberShareCoupon;
import org.jeecg.modules.demo.basemembersharecoupon.service.IBaseMemberShareCouponService;
import org.jeecg.modules.demo.basemembersharevip.entity.BaseMemberShareVip;
import org.jeecg.modules.demo.basemembersharevip.service.IBaseMemberShareVipService;
import org.jeecg.modules.demo.basemembertoreceivevip.entity.BaseMemberToReceiveVip;
import org.jeecg.modules.demo.basemembertoreceivevip.service.IBaseMemberToReceiveVipService;
import org.jeecg.modules.demo.basemembertoreceivevipcoupon.entity.BaseMemberToReceiveVipCoupon;
import org.jeecg.modules.demo.basemembertoreceivevipcoupon.service.IBaseMemberToReceiveVipCouponService;
import org.jeecg.modules.demo.basemembervip.service.IBaseMemberVipService;
import org.jeecg.modules.demo.basemembervipcoupon.service.IBaseMemberVipCouponService;
import org.jeecg.modules.demo.couponmanagement.entity.CouponManagement;
import org.jeecg.modules.demo.issuingrecords.entity.IssuingRecords;
import org.jeecg.modules.demo.issuingrecords.service.IIssuingRecordsService;
import org.jeecg.modules.demo.membermanagement.entity.MemberManagement;
import org.jeecg.modules.demo.membermanagement.service.IMemberManagementService;
import org.jeecg.modules.demo.msgtemplatelist.entity.MsgTemplate;
import org.jeecg.modules.demo.msgtemplatelist.service.IMsgTemplateService;
import org.jeecg.modules.demo.shareholdervipcard.service.IShareholderVipCardService;
import org.jeecg.modules.demo.stockmanage.entity.StockManage;
import org.jeecg.modules.demo.stockmanage.service.IStockManageService;
import org.jeecg.modules.demo.storeinfo.entity.StoreInfo;
import org.jeecg.modules.demo.storeinfo.service.IStoreInfoService;
import org.jeecg.modules.demo.vipcardcoupon.entity.VipCardCoupon;
import org.jeecg.modules.demo.vipcardcoupon.service.IVipCardCouponService;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.util.HttpUtils;
import org.jeecg.modules.weixin.util;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 全部贵宾卡
 * @Author: jeecg-boot
 * @Date: 2022-01-11
 * @Version: V1.0
 */
@Service
@Slf4j
public class AllVipcardServiceImpl extends ServiceImpl<AllVipcardMapper, AllVipcard> implements IAllVipcardService {
    @Resource
    private AllVipcardMapper allVipcardMapper;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private IIssuingRecordsService issuingRecordsService;
    @Autowired
    private IVipCardCouponService vipCardCouponService;
    @Autowired
    private IBaseMemberVipService baseMemberVipService;
    @Autowired
    private IBaseMemberVipCouponService baseMemberVipCouponService;
    @Autowired
    private IShareholderVipCardService shareholderVipCardService;
    @Autowired
    private IStockManageService stockManageService;
    @Autowired
    private IBaseMemberShareVipService baseMemberShareVipService;
    @Autowired
    private IBaseMemberShareCouponService baseMemberShareCouponService;
    @Autowired
    private IMemberManagementService memberManagementService;
    @Autowired
    private IBaseMemberToReceiveVipService baseMemberToReceiveVipService;
    @Autowired
    private IBaseMemberToReceiveVipCouponService baseMemberToReceiveVipCouponService;
    @Autowired
    private IStoreInfoService storeInfoService;
    @Autowired
    private IMsgTemplateService msgTemplateListService;

    @Override
    public int getCount(String vipId) {
        QueryWrapper<VipCardCoupon> query = new QueryWrapper<>();
        query.eq("vip_id", vipId);
        List<VipCardCoupon> vipCar = vipCardCouponService.list(query);
        int count = 0;
        for (VipCardCoupon v : vipCar) {
            count += v.getNum();
        }
        return count;
    }

    /**
     * 发卡（不包含生成二维码）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> setIssuing(String vipId, String ids, Integer num, String storeId) {
        //ids 既可能是会员，也可能是股东
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        AllVipcard av = getById(vipId);
        if (av == null) {
            return Result.error("没有查到贵宾卡记录");
        }
        if ("股东拓客卡".equals(av.getCardType()) && num <= 0) {
            return Result.error("下发失败，股东拓客卡下发数量需要大于0！");
        }
        if ("通用卡".equals(av.getCardType()) && num < 0) {
            return Result.error("下发失败，通用卡可赠送数量不能小于0！");
        }
        // 关联优惠劵数量
        List<VipCardCoupon> list = vipCardCouponService.list(new QueryWrapper<VipCardCoupon>()
                .eq("store_id", storeId)
                .eq("vip_id", av.getId()));
        Integer ticketNum = list.stream().map(VipCardCoupon::getNum).reduce(Integer::sum).orElse(0);
        if (ticketNum == 0) {
            return Result.error("贵宾卡还未关联优惠劵");
        }
        av.setTicketNum(ticketNum);
        if ("免费".equals(av.getIsFree())) {
            av.setSellingPrice(null);
        }
        // 发卡记录
        IssuingRecords issuing = new IssuingRecords();
        issuing.setDrawTime(new Date());
        issuing.setQuantityReceived(0);
        issuing.setCirculation(num);
        issuing.setToStoreNum(0);
        issuing.setOperator(sysUser.getRealname());
        issuing.setStoreId(storeId);
        issuing.setVipId(vipId);
        issuing.setVipName(av.getCardName());
        issuing.setCirculation(num);
        issuing.setCurrentAllowance(num + 1);

        // 贵宾卡关联的优惠劵，数量已从关联表中带出
        List<CouponManagement> cmList = allVipcardMapper.listCouponsByVipId(vipId, storeId);

        // 会员/股东id
        String[] idList = ids.split(",");

        MemberManagement mbmber = memberManagementService.getById(idList[0]);
        String workMode;
        if (mbmber == null) {
            workMode = "stock";
            issuing.setStockId(idList[0]);
        } else {
            workMode = "member";
        }

        if (idList.length == 1) {
            MemberManagement mm = null;
            if (workMode.equals("member")) {
                mm = memberManagementService.getById(idList[0]);
            } else {
                mm = getMemberByStockId(idList[0]);
            }
            issuing.setMemberId(mm.getId());
            issuing.setMemberName(mm.getName());
        } else {
            issuing.setMemberIds(ids);
        }

        issuingRecordsService.save(issuing);
        for (String vId : idList) {


            if ("通用卡".equals(av.getCardType())) {
                MemberManagement mm = null;
                if (workMode.equals("member")) {
                    mm = memberManagementService.getById(vId);
                } else {
                    mm = getMemberByStockId(vId);
                }
                // 待领取表增加数据
                BaseMemberToReceiveVip toReceiveVip = new BaseMemberToReceiveVip();
                BeanUtils.copyProperties(av, toReceiveVip);
                toReceiveVip.setId(null);
                toReceiveVip.setCreateTime(null);
                toReceiveVip.setCreateBy(null);
                toReceiveVip.setUpdateTime(null);
                toReceiveVip.setUpdateBy(null);
                toReceiveVip.setType("1");
                toReceiveVip.setMemberId(mm.getId());
                toReceiveVip.setIssuingRecordsId(issuing.getId());
                toReceiveVip.setStatus("0");
                toReceiveVip.setShareNum(num);
                baseMemberToReceiveVipService.save(toReceiveVip);

                // 复制到会员/股东可分享贵宾卡
                BaseMemberShareVip bmsv = new BaseMemberShareVip();
                BeanUtils.copyProperties(av, bmsv);
                bmsv.setId(null);
                bmsv.setCreateBy(null);
                bmsv.setCreateTime(null);
                bmsv.setUpdateBy(null);
                bmsv.setUpdateTime(null);
                bmsv.setRecordId(issuing.getId());
                bmsv.setStockId(ids);
                bmsv.setMemberId(mm.getId());
                bmsv.setNum(num);
                bmsv.setVedioId(av.getVedioId());
                baseMemberShareVipService.save(bmsv);

                for (CouponManagement coupon : cmList) {
                    BaseMemberToReceiveVipCoupon toReceiveVipCoupon = new BaseMemberToReceiveVipCoupon();
                    BeanUtils.copyProperties(coupon, toReceiveVipCoupon);
                    toReceiveVipCoupon.setId(null);
                    toReceiveVipCoupon.setCreateTime(null);
                    toReceiveVipCoupon.setCreateBy(null);
                    toReceiveVipCoupon.setUpdateTime(null);
                    toReceiveVipCoupon.setUpdateBy(null);
                    toReceiveVipCoupon.setToReceiveVipId(toReceiveVip.getId());
                    toReceiveVipCoupon.setMemberId(mm.getId());
                    toReceiveVipCoupon.setNum(Integer.parseInt(coupon.getNum()));
                    baseMemberToReceiveVipCouponService.save(toReceiveVipCoupon);
                }
                for (CouponManagement cm : cmList) {
                    // 复制到会员/股东可分享贵宾卡关联的优惠劵表
                    BaseMemberShareCoupon bmsc = new BaseMemberShareCoupon();
                    BeanUtils.copyProperties(cm, bmsc);
                    bmsc.setId(null);
                    bmsc.setCreateBy(null);
                    bmsc.setCreateTime(null);
                    bmsc.setUpdateBy(null);
                    bmsc.setUpdateTime(null);
                    bmsc.setShareVipId(bmsv.getId());
                    bmsc.setMemberId(mm.getId());
                    bmsc.setNum(Integer.parseInt(cm.getNum()));
                    baseMemberShareCouponService.save(bmsc);
                }
                // 模板消息
                try {
                    String gzhOpenId = mm.getGzhOpenId();
                    if (gzhOpenId == null) {
                        log.info("发送下发通用卡模板推送失败，会员未绑定公众号");
                    } else {
                        StoreInfo store = storeInfoService.getById(storeId);
                        String bossGzhOpenId = storeInfoService.getBossGzhOpenId(storeId);
                        if (store == null) {
                            log.info("发送下发通用卡模板推送失败，未查到店铺信息");
                        } else {
                            String gzhAppId = store.getGzhAppId();
                            String gzhAppSecret = store.getGzhAppSecret();
                            if (StringUtils.isEmpty(gzhAppId) || StringUtils.isEmpty(gzhAppSecret)) {
                                log.info("发送下发通用卡模板推送失败，店铺未绑定公众号");
                            } else {
                                String url1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + gzhAppId + "&secret=" + gzhAppSecret;
                                String result1 = HttpUtils.sendGet(url1);
                                JSONObject resultJson1 = JSON.parseObject(result1);
                                String errcode = resultJson1.getString("errcode");
                                if (errcode != null && !"0".equals(errcode)) {
                                    log.info("发送下发通用卡模板推送失败，获取accessToken返回值异常，错误码：{}", errcode);
                                } else {
                                    String accessToken = resultJson1.getString("access_token");
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日 HH:mm");
                                    MsgTemplate msgTemplate = msgTemplateListService.getByTitle("规划任务生成提醒", storeId);
                                    String templateId = msgTemplate.getTemplateId();
                                    util.unclaimedCardNotice(templateId, gzhOpenId, "通用卡", sdf.format(new Date()), store.getXcxAppId(), "shop/guest/info?vipId=" + toReceiveVip.getId() + "&type=3", accessToken);

                                    log.info("发送下发通用卡模板推送成功");
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("发送下发通用卡模板推送失败，发生异常", e);
                }
            }
            if ("股东拓客卡".equals(av.getCardType())) {
                StockManage sm = stockManageService.getById(vId);


                MemberManagement mm = null;
                if (workMode.equals("member")) {
                    mm = memberManagementService.getById(vId);
                } else {
                    mm = getMemberByStockId(vId);
                }
                // 复制到会员/股东可分享贵宾卡
                BaseMemberShareVip bmsv = new BaseMemberShareVip();
                BeanUtils.copyProperties(av, bmsv);
                bmsv.setId(null);
                bmsv.setCreateBy(null);
                bmsv.setCreateTime(null);
                bmsv.setUpdateBy(null);
                bmsv.setUpdateTime(null);
                bmsv.setRecordId(issuing.getId());
                bmsv.setStockId(vId);
                bmsv.setMemberId(mm.getId());
                bmsv.setNum(num);
                bmsv.setVedioId(av.getVedioId());
                baseMemberShareVipService.save(bmsv);
                for (CouponManagement cm : cmList) {
                    // 复制到会员/股东可分享贵宾卡关联的优惠劵表
                    BaseMemberShareCoupon bmsc = new BaseMemberShareCoupon();
                    BeanUtils.copyProperties(cm, bmsc);
                    bmsc.setId(null);
                    bmsc.setCreateBy(null);
                    bmsc.setCreateTime(null);
                    bmsc.setUpdateBy(null);
                    bmsc.setUpdateTime(null);
                    bmsc.setShareVipId(bmsv.getId());
                    bmsc.setMemberId(mm.getId());
                    bmsc.setNum(Integer.parseInt(cm.getNum()));
                    baseMemberShareCouponService.save(bmsc);
                }
                // 模板消息
                try {
                    //MemberManagement stockMember = memberManagementService.getById(sm.getMemberId());
                    String gzhOpenId = mm.getGzhOpenId();
                    if (gzhOpenId == null) {
                        log.info("发送下发拓客卡模板推送失败，股东未绑定公众号");
                    } else {
                        StoreInfo store = storeInfoService.getById(storeId);
                        if (store == null) {
                            log.info("发送下发拓客卡模板推送失败，未查到店铺信息");
                        } else {
                            String bossGzhOpenId = storeInfoService.getBossGzhOpenId(storeId);
                            String gzhAppId = store.getGzhAppId();
                            String gzhAppSecret = store.getGzhAppSecret();
                            if (StringUtils.isEmpty(gzhAppId) || StringUtils.isEmpty(gzhAppSecret)) {
                                log.info("发送下发拓客卡模板推送失败，店铺未绑定公众号");
                            } else {
                                String url1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + gzhAppId + "&secret=" + gzhAppSecret;
                                String result1 = HttpUtils.sendGet(url1);
                                JSONObject resultJson1 = JSON.parseObject(result1);
                                String errcode = resultJson1.getString("errcode");
                                if (errcode != null && !"0".equals(errcode)) {
                                    log.info("发送下发拓客卡模板推送失败，获取accessToken返回值异常，错误码：{}", errcode);
                                } else {
                                    String accessToken = resultJson1.getString("access_token");
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日 HH:mm");
                                    MsgTemplate msgTemplate = msgTemplateListService.getByTitle("规划任务生成提醒", storeId);
                                    String templateId = msgTemplate.getTemplateId();
                                    if (sm != null) {
                                        util.sendTokerCardNotice(templateId, sm.getStockName(), gzhOpenId, "股东拓客卡", sdf.format(new Date()), store.getXcxAppId(), "user/toker/index", accessToken);
                                    }

                                    log.info("发送下发拓客卡模板推送成功");
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("发送下发拓客卡模板推送失败，发生异常", e);
                }
            }
        }
        av.setCreditNumber(av.getCreditNumber() + 1);
        updateById(av);
        return Result.OK("下发成功！");
    }

    private MemberManagement getMemberByStockId(String stockId) {
        StockManage stock = stockManageService.getById(stockId);
        MemberManagement mm = memberManagementService.getById(stock.getMemberId());

        return mm;
    }

    /**
     * 为股东发卡
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> setIssuing4Stock(String vipId, String stockId, Integer num, String storeId) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        AllVipcard av = getById(vipId);
        if (av == null) {
            return Result.error("没有查到贵宾卡记录");
        }
        if (!"股东拓客卡".equals(av.getCardType())) {
            return Result.error("下发失败，只能是拓客卡！");
        }

        if (num <= 0) {
            return Result.error("下发失败，股东拓客卡下发数量需要大于0！");
        }


        // 关联优惠劵数量
        List<VipCardCoupon> list = vipCardCouponService.list(new QueryWrapper<VipCardCoupon>()
                .eq("store_id", storeId)
                .eq("vip_id", av.getId()));
        Integer ticketNum = list.stream().map(VipCardCoupon::getNum).reduce(Integer::sum).orElse(0);
        if (ticketNum == 0) {
            return Result.error("贵宾卡还未关联优惠劵");
        }
        av.setTicketNum(ticketNum);
        if ("免费".equals(av.getIsFree())) {
            av.setSellingPrice(null);
        }
        // 发卡记录
        IssuingRecords issuing = new IssuingRecords();
        issuing.setDrawTime(new Date());
        issuing.setQuantityReceived(0);
        issuing.setCirculation(num);
        issuing.setToStoreNum(0);
        if(sysUser!=null){
            issuing.setOperator(sysUser.getRealname());
        }
        issuing.setStoreId(storeId);
        issuing.setStockId(stockId);
        issuing.setVipId(vipId);
        issuing.setVipName(av.getCardName());
        issuing.setCirculation(num);
        issuing.setCurrentAllowance(num + 1);

        // 贵宾卡关联的优惠劵，数量已从关联表中带出
        List<CouponManagement> cmList = allVipcardMapper.listCouponsByVipId(vipId, storeId);

        // 会员/股东id
        String[] memberIdList = stockId.split(",");

        if (memberIdList.length == 1) {
            StockManage stock = stockManageService.getById(memberIdList[0]);
            MemberManagement mm = memberManagementService.getById(stock.getMemberId());
            issuing.setMemberId(stockId);
            issuing.setMemberName(mm.getName());
        } else {
//            issuing.setMemberIds();
        }

        issuingRecordsService.save(issuing);
        for (String vMemberId : memberIdList) {


            if ("通用卡".equals(av.getCardType())) {
                MemberManagement mm = memberManagementService.getById(vMemberId);
                // 待领取表增加数据
                BaseMemberToReceiveVip toReceiveVip = new BaseMemberToReceiveVip();
                BeanUtils.copyProperties(av, toReceiveVip);
                toReceiveVip.setId(null);
                toReceiveVip.setCreateTime(null);
                toReceiveVip.setCreateBy(null);
                toReceiveVip.setUpdateTime(null);
                toReceiveVip.setUpdateBy(null);
                toReceiveVip.setType("1");
                toReceiveVip.setMemberId(vMemberId);
                toReceiveVip.setIssuingRecordsId(issuing.getId());
                toReceiveVip.setStatus("0");
                toReceiveVip.setShareNum(num);
                baseMemberToReceiveVipService.save(toReceiveVip);

                // 复制到会员/股东可分享贵宾卡
                BaseMemberShareVip bmsv = new BaseMemberShareVip();
                BeanUtils.copyProperties(av, bmsv);
                bmsv.setId(null);
                bmsv.setCreateBy(null);
                bmsv.setCreateTime(null);
                bmsv.setUpdateBy(null);
                bmsv.setUpdateTime(null);
                bmsv.setRecordId(issuing.getId());
                bmsv.setStockId(stockId);
                bmsv.setMemberId(vMemberId);
                bmsv.setNum(num);
                bmsv.setVedioId(av.getVedioId());
                baseMemberShareVipService.save(bmsv);

                for (CouponManagement coupon : cmList) {
                    BaseMemberToReceiveVipCoupon toReceiveVipCoupon = new BaseMemberToReceiveVipCoupon();
                    BeanUtils.copyProperties(coupon, toReceiveVipCoupon);
                    toReceiveVipCoupon.setId(null);
                    toReceiveVipCoupon.setCreateTime(null);
                    toReceiveVipCoupon.setCreateBy(null);
                    toReceiveVipCoupon.setUpdateTime(null);
                    toReceiveVipCoupon.setUpdateBy(null);
                    toReceiveVipCoupon.setToReceiveVipId(toReceiveVip.getId());
                    toReceiveVipCoupon.setMemberId(vMemberId);
                    toReceiveVipCoupon.setNum(Integer.parseInt(coupon.getNum()));
                    baseMemberToReceiveVipCouponService.save(toReceiveVipCoupon);
                }
                for (CouponManagement cm : cmList) {
                    // 复制到会员/股东可分享贵宾卡关联的优惠劵表
                    BaseMemberShareCoupon bmsc = new BaseMemberShareCoupon();
                    BeanUtils.copyProperties(cm, bmsc);
                    bmsc.setId(null);
                    bmsc.setCreateBy(null);
                    bmsc.setCreateTime(null);
                    bmsc.setUpdateBy(null);
                    bmsc.setUpdateTime(null);
                    bmsc.setShareVipId(bmsv.getId());
                    bmsc.setMemberId(vMemberId);
                    bmsc.setNum(Integer.parseInt(cm.getNum()));
                    baseMemberShareCouponService.save(bmsc);
                }
                // 模板消息
                try {
                    String gzhOpenId = mm.getGzhOpenId();
                    if (gzhOpenId == null) {
                        log.info("发送下发通用卡模板推送失败，会员未绑定公众号");
                    } else {
                        StoreInfo store = storeInfoService.getById(storeId);
                        String bossGzhOpenId = storeInfoService.getBossGzhOpenId(storeId);
                        if (store == null) {
                            log.info("发送下发通用卡模板推送失败，未查到店铺信息");
                        } else {
                            String gzhAppId = store.getGzhAppId();
                            String gzhAppSecret = store.getGzhAppSecret();
                            if (StringUtils.isEmpty(gzhAppId) || StringUtils.isEmpty(gzhAppSecret)) {
                                log.info("发送下发通用卡模板推送失败，店铺未绑定公众号");
                            } else {
                                String url1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + gzhAppId + "&secret=" + gzhAppSecret;
                                String result1 = HttpUtils.sendGet(url1);
                                JSONObject resultJson1 = JSON.parseObject(result1);
                                String errcode = resultJson1.getString("errcode");
                                if (errcode != null && !"0".equals(errcode)) {
                                    log.info("发送下发通用卡模板推送失败，获取accessToken返回值异常，错误码：{}", errcode);
                                } else {
                                    String accessToken = resultJson1.getString("access_token");
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日 HH:mm");
                                    MsgTemplate msgTemplate = msgTemplateListService.getByTitle("规划任务生成提醒", storeId);
                                    String templateId = msgTemplate.getTemplateId();
                                    util.unclaimedCardNotice(templateId, gzhOpenId, "通用卡", sdf.format(new Date()), store.getXcxAppId(), "shop/guest/info?vipId=" + toReceiveVip.getId() + "&type=3", accessToken);

                                    log.info("发送下发通用卡模板推送成功");
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("发送下发通用卡模板推送失败，发生异常", e);
                }
            }
            if ("股东拓客卡".equals(av.getCardType())) {
                StockManage sm = stockManageService.getById(stockId);

                // 复制到会员/股东可分享贵宾卡
                BaseMemberShareVip bmsv = new BaseMemberShareVip();
                BeanUtils.copyProperties(av, bmsv);
                bmsv.setId(null);
                bmsv.setCreateBy(null);
                bmsv.setCreateTime(null);
                bmsv.setUpdateBy(null);
                bmsv.setUpdateTime(null);
                bmsv.setRecordId(issuing.getId());
                bmsv.setStockId(stockId);
                bmsv.setMemberId(sm.getMemberId());
                bmsv.setNum(num);
                bmsv.setVedioId(av.getVedioId());
                baseMemberShareVipService.save(bmsv);
                for (CouponManagement cm : cmList) {
                    // 复制到会员/股东可分享贵宾卡关联的优惠劵表
                    BaseMemberShareCoupon bmsc = new BaseMemberShareCoupon();
                    BeanUtils.copyProperties(cm, bmsc);
                    bmsc.setId(null);
                    bmsc.setCreateBy(null);
                    bmsc.setCreateTime(null);
                    bmsc.setUpdateBy(null);
                    bmsc.setUpdateTime(null);
                    bmsc.setShareVipId(bmsv.getId());
                    bmsc.setMemberId(vMemberId);
                    bmsc.setNum(Integer.parseInt(cm.getNum()));
                    baseMemberShareCouponService.save(bmsc);
                }
                // 模板消息
                try {
                    MemberManagement stockMember = memberManagementService.getById(sm.getMemberId());
                    String gzhOpenId = stockMember.getGzhOpenId();
                    if (gzhOpenId == null) {
                        log.info("发送下发拓客卡模板推送失败，股东未绑定公众号");
                    } else {
                        StoreInfo store = storeInfoService.getById(storeId);
                        if (store == null) {
                            log.info("发送下发拓客卡模板推送失败，未查到店铺信息");
                        } else {
                            String bossGzhOpenId = storeInfoService.getBossGzhOpenId(storeId);
                            String gzhAppId = store.getGzhAppId();
                            String gzhAppSecret = store.getGzhAppSecret();
                            if (StringUtils.isEmpty(gzhAppId) || StringUtils.isEmpty(gzhAppSecret)) {
                                log.info("发送下发拓客卡模板推送失败，店铺未绑定公众号");
                            } else {
                                String url1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + gzhAppId + "&secret=" + gzhAppSecret;
                                String result1 = HttpUtils.sendGet(url1);
                                JSONObject resultJson1 = JSON.parseObject(result1);
                                String errcode = resultJson1.getString("errcode");
                                if (errcode != null && !"0".equals(errcode)) {
                                    log.info("发送下发拓客卡模板推送失败，获取accessToken返回值异常，错误码：{}", errcode);
                                } else {
                                    String accessToken = resultJson1.getString("access_token");
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日 HH:mm");
                                    MsgTemplate msgTemplate = msgTemplateListService.getByTitle("规划任务生成提醒", storeId);
                                    String templateId = msgTemplate.getTemplateId();
                                    util.sendTokerCardNotice(templateId, sm.getStockName(), gzhOpenId, "股东拓客卡", sdf.format(new Date()), store.getXcxAppId(), "user/toker/index", accessToken);

                                    log.info("发送下发拓客卡模板推送成功");
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("发送下发拓客卡模板推送失败，发生异常", e);
                }
            }
        }
        av.setCreditNumber(av.getCreditNumber() + 1);
        updateById(av);
        return Result.OK("下发成功！");
    }

    //查询已下发贵宾卡数量
    @Override
    public String getGrantedCardQty(String storeId) {
        return allVipcardMapper.getGrantedCardQty(storeId);
    }

    @Override
    public IPage<CouponManagement> queryCouponList(Page<CouponManagement> page, Map<String, Object> params) {
        return allVipcardMapper.queryCouponList(page, params);
    }

    @Override
    public List<CouponManagement> listCouponsByVipId(String vipId, String storeId) {
        return allVipcardMapper.listCouponsByVipId(vipId, storeId);
    }
}
